package com.gree.flowable.modeler.security;

import com.gree.framework.entity.SysUser;
import com.gree.framework.utils.SecurityUtils;
import org.flowable.ui.common.model.RemoteUser;
import org.flowable.ui.common.security.FlowableAppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import static com.gree.flowable.modeler.tools.constants.FlowableConstants.FLOW_ABLE_MODELER_ROLES;

@Service
public class MyUserDetailsService implements UserDetailsService {

    private Logger LOGGER = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LOGGER.debug("MyUserDetailsService:loadUserByUsername:认证权限.....");
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();

        // 配置 flowable-modeler 权限
        FLOW_ABLE_MODELER_ROLES.parallelStream().forEach(obj -> {
            authorities.add(new SimpleGrantedAuthority(obj));
        });

        String clientId = SecurityUtils.getClientId();
        RemoteUser sourceUser = new RemoteUser();
        SysUser loginUser = SecurityUtils.getUser().getUser();
        if ("gscm_client".equals(clientId)){
            sourceUser.setFirstName(loginUser.getNama());
            sourceUser.setDisplayName(loginUser.getNama());
            sourceUser.setPassword(loginUser.getPawd());
            sourceUser.setId(loginUser.getUsid());
        }else {
            String systemName = SecurityUtils.getUser().getUsername();
            sourceUser.setFirstName(systemName);
            sourceUser.setDisplayName("null");
            sourceUser.setPassword("123456");
            sourceUser.setId(systemName);
            sourceUser.setTenantId(systemName);
        }
        sourceUser.setPrivileges(new ArrayList<>(FLOW_ABLE_MODELER_ROLES));

        FlowableAppUser user = new FlowableAppUser(sourceUser, sourceUser.getId(), authorities);
        return user;
    }
}
